package com.flame.file.controller;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.flame.core.protocol.PageResult;
import com.flame.core.protocol.Result;
import com.flame.core.utils.HttpUtils;
import com.flame.file.controller.vo.FileInfoVo;
import com.flame.file.entity.FileInfo;
import com.flame.file.exception.FileInfoExceptionMessage;
import com.flame.file.exception.FileInfoRuntimeException;
import com.flame.file.service.FileInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * flame_sys_file_info 系统文件表
 *
 * @author 吴欣童
 * @since 2022-11-28 13:50:59
 */
@RestController
public class FileInfoController {

    @Autowired
    private FileInfoService fileInfoService;

    @PostMapping("/file/download")
    public void downloadFile(@RequestBody FileInfo fileInfo, HttpServletResponse response) {
        FileInfo dbFileInfo = fileInfoService.findById(fileInfo.getFileId());
        if (dbFileInfo == null) {
            throw new FileInfoRuntimeException(FileInfoExceptionMessage.FILEINFO_NOT_EXIST);
        }
        String fileFullName = dbFileInfo.getFileName();
        if (StringUtils.hasText(dbFileInfo.getFileType())) {
            fileFullName = fileFullName + "." + dbFileInfo.getFileType();
        }
        HttpUtils.writeFile(response, fileFullName, dbFileInfo.getFileLocation(), false);
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/file/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        return Result.success(fileInfoService.save(file));
    }

    @PostMapping("/file/page")
    public PageResult pageFileInfo(@RequestBody FileInfoVo fileInfoVo) {
        return PageResult.success(fileInfoService.pageFileInfo(fileInfoVo));
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/file/delete")
    public Result deleteFileInfo(@RequestBody @Validated FileInfo fileInfo) {
        fileInfoService.deleteFileInfo(fileInfo.getFileId());
        return Result.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/file/batch/delete")
    public Result batchDeleteFileInfo(@RequestBody List<Long> fileIdList) {
        for (Long fileId : fileIdList) {
            fileInfoService.deleteFileInfo(fileId);
        }
        return Result.success();
    }
}
